#!/usr/bin/env node
/**
 * Created by udi on 17-7-14.
 */
'use strict';

var program = require('commander');

var fs = require("./util/async_file")
var jv = require("./util/jv")
var path = require('path');
var watch = require('node-watch');
var packjson = require("./package.json");
//var exec = require('child_process').exec;
var print = function (msg) {
  if (!msg) return;
  process.stdout.write("[" + (new Date().toString()) + "]" + msg);
}
// const {rmdir} = require('commandir')
//var fs = require("fs")

var cmd = program
  .version(packjson.version)
  .description(packjson.description)
  .usage('[--config 配置文件] <-w --watch 监视模式>')
  .option('--config [配置文件]', "")
  .option('-w, --watch [监视模式]', '')
  .parse(process.argv);

if (!cmd.config) {
  cmd.outputHelp();
  return -1;
}

var config = path.resolve(cmd.config);

var configPath = path.dirname(config) + "/";

(async function () {
  var _content = await fs.readFileAsync(config, 'utf8');
  var configJson = JSON.parse(_content);
  var files = configJson["files"];


  //核函数。
  var handleFile = async function (sourceFile, targetFile, varJson) {
    var content = await fs.readFileAsync(sourceFile, 'utf8');
    var txts = content.split("\n");
    var beginZhushi = false;
    for (var len = txts.length, i = 0; i < len; i++) {
      var line = txts[i];

      if (line == "") continue;
      if (beginZhushi) {
        if (line.endsWith("*/")) {
          beginZhushi = false
          continue;
        }
      }

      if (line.startsWith("//")) continue;
      if (line.startsWith("/*")) {
        beginZhushi = true;
        continue;
      }

      if (line.trim().startsWith("@") == false) {
        break;
      }


      //变量三部分: @var:值;
      var key = line.split(":")[0].trim();
      if (key in varJson) {
        var value = varJson[key];

        txts[i] = key + ": " + value + ";";
      }
    }


    fs.writeFileSync(targetFile, txts.join("\n"));
  }


  var var_json = configJson["var"];


  Object.keys(files).forEach(async file => {
    var source = file;
    if (file.startsWith("./") || file.startsWith("../")) {
      source = path.normalize(configPath + file);
    }
 
    Object.keys(var_json).forEach(async var_key => {
      var var_value = var_json[var_key];
      var target = files[file].replace("@var", var_key).replace("{var}", var_key);
      if (target.startsWith("./") || target.startsWith("../")) {
        target = path.normalize(configPath + target);
      }

      await handleFile(source, target, var_value);
    });


    if (cmd.watch) {
      watch(source, { recursive: false },   function (evt, name) {
        print(evt + ':' + name); 

        Object.keys(var_json).forEach(  var_key => {
          var var_value = var_json[var_key];
          var target = files[file].replace("@var", var_key).replace("{var}", var_key);
          if (target.startsWith("./") || target.startsWith("../")) {
            target = path.normalize(configPath + target);
          }

          if (evt == "remove") {
            if (fs.existsSync(target) == false) return;
            jv.rm(target);
          }  

          if (evt == "update" ) {
            console.log("update " + name +" ... ")
            handleFile(source, target, var_value);
          }
        }); 
  
        console.log( name + "\t\t(ok!)")
      });
    }

  });



  //console.log("¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯")
  console.log("编译完成!");
  return 0;
})();




